module API::V3
  class Terminals < Grape::API
    resource :terminals do
      get 'speed' do
        present({up: Settings.terminal_speed.up, down: Settings.terminal_speed.down})
      end

      params do
        requires :mac, type: String, regexp: CommonRegex::MAC
        requires :version, type: String
      end
      post 'version' do
        terminal = Terminal.find_by_mac(params[:mac])
        if terminal
          result = terminal.update_attributes(ip: request.ip, :version => params[:version])
        else
          result = false
        end
        present result: result
      end

      params do
        requires :name, type: String
        requires :current_version, type: String
      end
      get :version do
        branch = ['public', 'middleware', 'bootimage'].include?(params[:branch].to_s.downcase) ? params[:branch].to_s.downcase : 'public'
        client_terminalversion = TerminalVersion.where(
          version: params[:current_version], 
          release: true,
          name: params[:name],
          branch: branch
        ).first
        if client_terminalversion == nil
          present :result, false
          present :message, 'invalid client version'
          present :error_code, 1
        else
          present :result, true
          latest_terminalversion = client_terminalversion
          enforce = false
          TerminalVersion.where(release: true, name: params[:name]).each do |terminalversion|
            latest_terminalversion = terminalversion if terminalversion.is_greater?(latest_terminalversion)
            enforce ||= terminalversion.enforce if terminalversion.is_greater?(client_terminalversion)
          end

          if latest_terminalversion == client_terminalversion
            present :is_latest, true
          else
            present :is_latest, false
            present :release_version, latest_terminalversion.version
            present :changelog, latest_terminalversion.note
            link = request.scheme + '://' + request.host_with_port + latest_terminalversion.file.url.to_s
            present :link, link
            present :enforce, enforce
          end
        end
      end
    end
  end
end